/**
 * @filename:QuotationServiceImpl 2021-11-09 01:40:37
 * @project com/lwl/blue  V1.0
 * Copyright(c) 2018 <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a> Co. Ltd.
 * All right reserved.
 */
package com.lwl.blue.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lwl.blue.commont.base.*;
import com.lwl.blue.commont.utils.*;
import com.lwl.blue.dao.QuotationDao;
import com.lwl.blue.entity.*;
import com.lwl.blue.excel.quotation.CreateQuotationExport;
import com.lwl.blue.excel.quotation.QuotationDetailExport;
import com.lwl.blue.excel.quotation.QuotationExport;
import com.lwl.blue.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>自定义serviceImpl写在这里</p>
 *
 * <p>说明： 报价单服务实现层</P>
 *
 * @version: V1.0
 * @author: <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a>
 */
@Service
@Slf4j
public class QuotationServiceImpl extends ServiceImpl<QuotationDao, Quotation> implements QuotationService {
    @Value("${upload.filePath}")
    private String filePath;
    @Resource
    private QuotationDao quotationDao;
    @Resource
    QuotationDetailService quotationDetailService;
    @Resource
    ContractDetailService contractDetailService;
    @Resource
    ContractService contractService;
    @Resource
    CustomerService customerService;
    @Resource
    ExportModelConfigService exportModelConfigService;
    @Resource
    ItemService itemService;
    @Override
    public JsonResult<Page<Quotation>> pages(PageParam<Quotation> pageParam) {
        Page<Quotation> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
        return new JsonResult<Page<Quotation>>().success(quotationDao.pages(page, pageParam.getParam()));
    }

    @Override
    @Transactional
    public void deleteQuotation(Integer id) {
        quotationDao.update(null, new UpdateWrapper<Quotation>().lambda()
                .set(Quotation::getIsDelete, Const.IS_DELETE_YES)
                .set(Quotation::getUpdateUser, UserContextUtil.getUser().getUserName())
                .eq(Quotation::getId, id));
        quotationDetailService.update(new UpdateWrapper<QuotationDetail>().lambda()
                .set(QuotationDetail::getIsDelete, Const.IS_DELETE_YES)
                .set(QuotationDetail::getUpdateUser, UserContextUtil.getUser().getUserName())
                .eq(QuotationDetail::getQuotationId, id));
    }

    @Override
    @Transactional
    public JsonResult addContractByQuotation(Integer id) {
        Quotation quotation = quotationDao.selectById(id);
        if (null == quotation) {
            throw new BizException(ErrorCode.DATA_NOT_EXIST_ERROR.getCode(), ErrorCode.DATA_NOT_EXIST_ERROR.getMsg());
        }
        List<QuotationDetail> quotationDetailList = quotationDetailService.list(new QueryWrapper<QuotationDetail>()
                .lambda()
                .eq(QuotationDetail::getQuotationId, id)
                .eq(QuotationDetail::getIsDelete, 0));
        if (CollectionUtils.isEmpty(quotationDetailList)) {
            throw new BizException(ErrorCode.QUO_DETAIL_NOT_EXIST_ERROR.getCode(), ErrorCode.QUO_DETAIL_NOT_EXIST_ERROR.getMsg());
        }
        Contract contract = new Contract();
        BeanUtils.copyProperties(quotation, contract, "id");
        contract.setQuotationId(id);
        contractService.save(contract);
        List<ContractDetail> contractDetailList = new ArrayList<>();
        quotationDetailList.forEach(quotationDetail -> {
            ContractDetail detail = new ContractDetail();
            BeanUtils.copyProperties(quotationDetail, detail, "id");
            detail.setContractId(contract.getId());
            contractDetailList.add(detail);
        });
        contractDetailService.saveBatch(contractDetailList);
        return new JsonResult().success("生成订单信息成功，请到客人订单信息查看");
    }

    @Override
    @Transactional
    public void createQuotation(HttpServletResponse response, Integer id) {
        Quotation quotation = quotationDao.selectById(id);
        List<QuotationDetail> list = quotationDetailService.list(new QueryWrapper<QuotationDetail>()
                .lambda().eq(QuotationDetail::getQuotationId, id)
                .eq(QuotationDetail::getIsDelete, 0));
        List<CreateQuotationExport> exportList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(l -> {
                CreateQuotationExport c = new CreateQuotationExport();
                c.setHarborFor(quotation.getHarborFor());
                c.setCurrencyCode(quotation.getCurrencyCode());
                BeanUtils.copyProperties(l, c);
                exportList.add(c);
            });
        }
        try {
            EasyExcelUtils.export(response, "报价单", CreateQuotationExport.class, exportList);
        } catch (IOException e) {
            log.error("报检单生成失败：请求参数:id=" + id + "异常信息：e{}", e.getMessage());
        }
    }

    @Override
    public List<Quotation> getExportList(Quotation quotation) {
        if (!org.springframework.util.CollectionUtils.isEmpty(quotation.getIdBatch())) {
            List<Integer> idBatch = quotation.getIdBatch();
            quotation = new Quotation();
            quotation.setIdBatch(idBatch);
        }
        return quotationDao.pages(quotation);
    }

    @Override
    @Transactional
    public JsonResult copyQuotation(Integer id) {
        Quotation quotation = quotationDao.selectById(id);
        Quotation add = new Quotation();
        BeanUtils.copyProperties(quotation, add);
        add.setId(null);
        add.setQuotationNo(null);
        add.setQuotationName(null);
        add.setCreateTime(new Date());
        add.setCreateUser(CurrentUser.getUserInfo().getUserName());
        quotationDao.insert(add);
        List<QuotationDetail> quotationDetailList = quotationDetailService.list(new QueryWrapper<QuotationDetail>().lambda()
                .eq(QuotationDetail::getQuotationId, quotation.getId()));
        if (!CollectionUtils.isEmpty(quotationDetailList)) {
            List<QuotationDetail> addList = new ArrayList<>();
            quotationDetailList.forEach(
                    quotationDetail -> {
                        QuotationDetail addDetail = new QuotationDetail();
                        BeanUtils.copyProperties(quotationDetail, addDetail, "id");
                        addDetail.setQuotationId(add.getId());
                        addDetail.setCreateTime(new Date());
                        addDetail.setCreateUser(CurrentUser.getUserInfo().getUserName());
                        addList.add(addDetail);
                    }
            );
            quotationDetailService.saveBatch(addList);
        }
        return new JsonResult().success("复制成功");
    }

    @Override
    public void exportByCustomer(HttpServletResponse response, Integer quotationId) {
       String templateFileName = ExcelTemplateUtil.getQuotationExcelTemplatePathByCustomerId(filePath,quotationId);
       export(response,quotationId,templateFileName,1);
    }

    @Override
    public void export(HttpServletResponse response, Integer quotationId, Integer exportId) {
        ExportModelConfig exportModelConfig = exportModelConfigService.getFilePath(exportId);
        export(response,quotationId,exportModelConfig.getUrl(),exportModelConfig.getStatus());
    }

    @Override
    @Transactional
    public void saveUpdateData(Quotation quotation) {
        super.saveOrUpdate(quotation);
        if(!CollectionUtils.isEmpty(quotation.getItemIds())){
            ArrayList<Item> items = (ArrayList)itemService.listByIds(quotation.getItemIds());
            if(!CollectionUtils.isEmpty(items)){
                List<QuotationDetail> addList=new ArrayList(items.size());
                for (Item item:items){
                    QuotationDetail detail=new QuotationDetail();
                    BeanUtils.copyProperties(item,detail);
                    detail.setQuotationId(quotation.getId());
                    addList.add(detail);
                }
                quotationDetailService.saveBatch(addList);
            }
        }
    }

    private void export(HttpServletResponse response, Integer quotationId,String templateFileName,int reDateLevel) {
        Quotation quotation = quotationDao.selectById(quotationId);
        List<QuotationDetail> detailList = quotationDetailService.list(new QueryWrapper<QuotationDetail>()
                .lambda()
                .eq(QuotationDetail::getQuotationId, quotationId)
                .eq(QuotationDetail::getIsDelete,0)
        );
        if(detailList.isEmpty()){
            throw new BizException(ErrorCode.CONTRACT_DETAIL_NOT_EXIST_ERROR.getCode(),ErrorCode.CONTRACT_DETAIL_NOT_EXIST_ERROR.getMsg());
        }
        QuotationExport quotationExport=new QuotationExport();
        BeanUtils.copyProperties(quotation, quotationExport);
        Customer customer = customerService.getById(quotation.getCustomerId());
        quotationExport.setCustomerName(customer.getCustomerName());
        List<QuotationDetailExport> list = new ArrayList<>();
        for (QuotationDetail d : detailList) {
            QuotationDetailExport c = new QuotationDetailExport();
            BeanUtils.copyProperties(quotationExport, c);
            BeanUtils.copyProperties(d, c);
            c.setPhoto(EasyExcelUtils.getURL(d.getPhoto()));
            UnitChangeUtil.getInchDate(c, QuotationDetailExport.class);
            list.add(c);
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            File file=new File(templateFileName);
            if(file.exists()){
                String rFileName = URLEncoder.encode(customer.getCustomerName()+"报价单", "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + rFileName + ".xlsx");
                ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templateFileName).build();
                WriteSheet writeSheet = EasyExcel.writerSheet().build();
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
                if((reDateLevel&1)==1){
                    excelWriter.fill(quotationExport, writeSheet);
                }
                if((reDateLevel&2)==2){
                    // 如果有多个list 模板上必须有{前缀.} 这里的前缀就是 data1，然后多个list必须用 FillWrapper包裹
                    excelWriter.fill(new FillWrapper("list", list), fillConfig, writeSheet);
                }
                // 别忘记关闭流
                excelWriter.finish();
            }else {
                throw new BizException(ErrorCode.TEMPLATE_NOT_EXPORT_ERROR.getCode(),ErrorCode.SYS_EXCEPTION.getMsg());
            }
        }catch (BizException bizException){
            throw bizException;
        }catch (Exception exception) {
            exception.printStackTrace();
            throw new BizException(ErrorCode.SYS_EXCEPTION.getCode(),ErrorCode.SYS_EXCEPTION.getMsg());
        }
    }
}